package com.hmall.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.hmall.common.dto.ItemDTO;
import com.hmall.common.dto.PageDTO;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {

    @Autowired
    private ItemMapper itemMapper;

    @Override
    public PageDTO<Item> itemPageQuery(int page, int size) {
        PageHelper.startPage(page,size);
        List<Item> itemList = itemMapper.itemPageQuery();
        Long total = itemMapper.getItemTotal();
        PageDTO<Item> pageDTO = new PageDTO(total,itemList);
        return pageDTO;
    }

    @Override
    public ItemDTO selectItemById(Long id) {
        Item item = itemMapper.selectItemById(id);
        ItemDTO itemDTO = new ItemDTO();
        BeanUtils.copyProperties(item,itemDTO);
        return itemDTO;
    }

    @Override
    public void insertItem(Item item) {
        item.setSold(0);
        item.setCommentCount(0);
        item.setStatus(1);
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        itemMapper.insertItem(item);
    }

    @Override
    public void updateStatus(Long id, Integer status) {
        Item item = itemMapper.selectItemById(id);
        item.setStatus(status);
        itemMapper.updateItem(item);
    }

    @Override
    public void updateItem(ItemDTO itemDTO) {
        Item item = new Item();
        BeanUtils.copyProperties(itemDTO,item);
        item.setUpdateTime(new Date());
        itemMapper.updateItem(item);
    }

    @Override
    public void deleteItem(Long id) {
        itemMapper.deleteItem(id);
    }

    @Override
    public void substractStock(Long itemId, Integer num) {
        Item item = itemMapper.selectItemById(itemId);
        if (item.getStock()<num){
            throw new RuntimeException("库存不足");
        }
        item.setStock(item.getStock()-num);
        itemMapper.updateItem(item);
    }
}
